/*
 * @Description: 判断某个路由是否有权限 allOf：全部权限都有才显示 oneOf：只要有其中某个权限就显示 except：有某个权限就不显示
 * @Author: liushuang
 * @Date: 2022-03-26 12:05:22
 * @LastEditTime: 2022-08-29 17:26:08
 */
import store from '@/store'

export function can(roles, value) {
  let hasRoleFlag = false
  if (
    value instanceof Object
    && Object.prototype.hasOwnProperty.call(value, 'role')
    && Object.prototype.hasOwnProperty.call(value, 'mode')
  ) {
    const { role, mode } = value
    if (mode === 'allOf') {
      hasRoleFlag = role.every((item) => roles.some((r) => r.code === item))
    }
    if (mode === 'oneOf') {
      hasRoleFlag = role.some((item) => roles.some((r) => r.code === item))
    }
    if (mode === 'except') {
      hasRoleFlag = !role.some((item) => roles.some((r) => r.code === item))
    }
  }
  return hasRoleFlag
}

export function hasRole(value) {
  if (store.getters['user/admin']) return true
  if (value instanceof Array && value.length > 0) {
    return can(store.getters['user/roles'], {
      role: value,
      mode: 'oneOf'
    })
  }
  let mode = 'oneOf'
  if (Object.prototype.hasOwnProperty.call(value, 'mode')) mode = value.mode
  let result = true
  if (Object.prototype.hasOwnProperty.call(value, 'role')) {
    result = result && can(store.getters['user/roles'], { role: value.role, mode })
  }
  return result
}
